package com.xuyunceng.xinlin.cont;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.xuyunceng.xinlin.entity.User;
import com.xuyunceng.xinlin.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private UserService userService;

	private RequestCache requestCache = new HttpSessionRequestCache();
	
	private RedirectStrategy redirectStrategy;
	
//	private SessionStrategy strategy = new HttpSession;
	
	@RequestMapping("/reqaut")//当需要身份认证的时候跳转到这里
	@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
	public SimpleRes reqAuth(HttpServletRequest req,HttpServletResponse res) throws IOException {
		
		SavedRequest savedRequest = requestCache.getRequest(req, res);
	
		if (savedRequest!= null) {
			String targetUrl = savedRequest.getRedirectUrl();
			logger.info(targetUrl);
			if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
				redirectStrategy.sendRedirect(req, res, "");
			}
		}
		return new SimpleRes("访问的服务需要身份认账认证");
	}
	
	@PostMapping("/register")
	public User register(@Valid User user, BindingResult bindingResult) {
		return userService.register(user);
	}
	
	@GetMapping("/code/sms")
	public void createSmsCode(HttpSession httpSession) {
		
		
	}

	@GetMapping("/{id}")
	public User getOneUser(@PathVariable Long id) {
		return userService.idOneUser(id);
	}
	
	@DeleteMapping("/{id}")
	public void delUser(@PathVariable Long id) {
		userService.delUser(id);
	}

}
